/**
 * 
 */
package kr.co.insoft.framework.config;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;

import org.springframework.security.core.GrantedAuthority;

/**
 * @author IN-SOFT Inc. GoodwillDD(sylee@in-soft.co.kr)
 * 
 */
public class AuthUtil {
	public static List<String> getInitNormalUserAuth() {
		List<String> auths = new ArrayList<String>();
		StringBuffer menuAuth = null;
		for(Menus menus : Menus.getNormalUserDefaultMenus()) {
			menuAuth = new StringBuffer();
			menuAuth.append(Menus.MENU_PREFIX);
			menuAuth.append(menus.getMenuId());
			menuAuth.append(Menus.authSeparator);
			menuAuth.append(Authorities.getFullAccessAuth());
			auths.add(menuAuth.toString());
		}
		return auths;
	}

	public static List<String> getInitCompanyUserAuth() {
		List<String> auths = new ArrayList<String>();
		StringBuffer menuAuth = null;
		for(Menus menus : Menus.getCompanyUserDefaultMenus()) {
			menuAuth = new StringBuffer();
			menuAuth.append(Menus.MENU_PREFIX);
			menuAuth.append(menus.getMenuId());
			menuAuth.append(Menus.authSeparator);
			menuAuth.append(Authorities.getViewAccessAuth());
			auths.add(menuAuth.toString());
		}
		return auths;
	}

	/**
	 * 현재 메뉴에 해당하는 권한 목록을 반환한다.
	 * 
	 * @param menu
	 * @param auths
	 * @return
	 */
	public static HashSet<Authorities> getEnabledMenuAuth(Menus menu,
			Collection<? extends GrantedAuthority> auths) {
		HashSet<Authorities> result = new HashSet<Authorities>();
		String tmp[] = null;
		for (GrantedAuthority auth : auths) {
			if (auth.getAuthority().startsWith(Menus.MENU_PREFIX)) {
				tmp = auth.getAuthority().split(Menus.authSeparator);
				tmp[0] = tmp[0].replace(Menus.MENU_PREFIX, "");
				if (Menus.isEnabledMenu(tmp[0], menu)) { // 현재 메뉴가 사용 가능한지 확인
					result.addAll(Authorities.getDecodeAuth(tmp[1]));
				}
			}
		}
		return result;
	}
}
